package org.lds.logger.config.appender;

import lombok.Setter;
import org.lds.logger.config.LifeCycle;
import org.lds.logger.config.filter.AbstractAppenderFilter;
import org.lds.logger.config.layout.Layout;
import org.lds.logger.event.LoggerEvent;

import java.util.List;

@Setter
public abstract class AbstractAppender implements Appender, LifeCycle {
    private String name;
    private String destination;
    private int priority;
    private AbstractAppenderFilter appenderFilter;
    private Layout layout;

    public AbstractAppender() {
    }

    public AbstractAppender(String name, String destination, int priority, AbstractAppenderFilter appenderFilter, Layout layout) {
        this.name = name;
        this.destination = destination;
        this.priority = priority;
        this.appenderFilter = appenderFilter;
        this.layout = layout;
    }

    @Override
    public String getDestination() {
        return destination;
    }

    @Override
    public AbstractAppenderFilter getAppenderFilter() {
        return appenderFilter;
    }

    @Override
    public Layout getLayout() {
        return layout;
    }

    @Override
    public int getPriority() {
        return priority;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public void initialize() {

    }

    private void append(String message) {
        if (beforeAppend(message)) {
            doAppend(message);
        }
    }

    protected void doAppend(String message) {

    }

    protected boolean beforeAppend(String message) {
        return true;
    }

    @Override
    public void append(LoggerEvent loggerEvent) {
        append(getLayout().format(loggerEvent));
    }

    @Override
    public void append(List<LoggerEvent> loggerEvents) {
        Layout layout = getLayout();
        StringBuilder builder = new StringBuilder();
        for (LoggerEvent loggerEvent : loggerEvents) {
            builder.append(layout.format(loggerEvent));
        }
        append(builder.toString());
    }
}
